
package com.cha.chaCommon.redis.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/**
 * 从spring容器中获取对象
 */

@Component
public class SpringBeanUtils implements ApplicationContextAware {


/**
     * Spring应用上下文对象
     * 通过该对象可以从spring容器中获取对象
     */

    private static ApplicationContext applicationContext = null;


/**
     * 注入上下文对象
     *
     * @param applicationContext
     * @throws BeansException
     */

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtils.applicationContext = applicationContext;
    }


/**
     * 根据名称获取bean对象
     *
     * @param name
     * @param <T>
     * @return
     * @throws BeansException
     */

    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }


/**
     * 根据类型获取bean对象
     *
     * @param clz
     * @param <T>
     * @return
     */

    public static <T> T getBean(Class<T> clz) {
        T result = (T) applicationContext.getBean(clz);
        return result;
    }

}

